<?php

function escapeXMlString($str)
{
	//remove all the &nbsp
	$p1="/'/" ; $p1n="&apos;";
	$p2='/"/' ; $p2n="&quot;";
	$p3="/</" ; $p3n="&lt;";
	$p4="/>/" ; $p4n="&gt;";
	$p5="/&/" ; $p5n="&amp;";
	$str=preg_replace($p1, $p1n, $str);
	$str=preg_replace($p2, $p2n, $str);
	$str=preg_replace($p3, $p3n, $str);
	$str=preg_replace($p4, $p4n, $str);
	$str=preg_replace($p5, $p5n, $str);
	return $str;
}
//if it is only   
function isValidParagraph($str)
{
	if(preg_match("/[\x{4e00}-\x{9fa5}]+/u",$str)){
		return true ;
	}
	return false;
}
	
//the var is $chapter
//open a file to write
$filename=preg_replace("/.htm$|.html$/", ".xml" ,$file);
$handle = fopen($filename, "w");
fwrite($handle,"<?xml version='1.0' encoding='UTF-8' ?>\n");
fwrite($handle,"<chapter>");

fwrite($handle,"<index>");
$chapter_index=escapeXMLString($chapter_index);
fwrite($handle,$chapter_index);
fwrite($handle,"</index>\n");

fwrite($handle,"<title>"); 
$chapter_index=escapeXMLString($chapter_title);
fwrite($handle,$chapter_title);
fwrite($handle,"</title>\n");

foreach ($chapter_paragraphes as $p){
    $p=escapeXMLString($p);
    if(isValidParagraph($p)){
        fwrite($handle,"<p>");
        fwrite($handle,$p);
        fwrite($handle,"</p>\n");
    }
}

fwrite($handle,"</chapter>");
fclose($handle);
?>
